import _city from "../../../cache/_city";
import _layer from "../../../common/_layer";
import _object from "../../../utils/_object";
import lib_activity from "../../../api/lib_activity";
import lib_city from "../../../api/lib_city";
import lib_car from "../../../api/lib_car"
import _series from "../../../cache/_series";
import _location from "../../../cache/_location";
import _throttle from "../../../utils/_throttle"
import _time from "../../../utils/_time";
import _activity from "../../../cache/_activity";


Page({
  data: {
    searchValue: '', //搜索
    allDataList: [],
    filteredDataList: [],
    activity_id: '', //活动ID
    tids: 0, // 模板ID
    channel: 3, //渠道
    custom_car: 0, // 是否自定义车型库 -- 不考虑自定义车型
    tid: 0, // 有无车型库
    share_theme: '', //分享描述
    stime: 0, // 项目开始时间
    etime: 0, // 项目结束时间
    province: '', //省
    city: '', //城市
    location: '', //定位
    citys: [],
    is_stop: false,
    ui: {},
    clickid: '', //点击上报id

  },
  onLoad: function (options) {

    //项目ID参数
    if (_object._length(options) > 0 && options.hasOwnProperty('tids') && options.tids > 0) {
      //设置项目缓存
      this.setData({
        tids: options.tids
      })
    } else {
      this.setData({
        tids: 682
      })
    }
    //设置项目缓存
    if (_object._length(options) > 0 && options.hasOwnProperty('activity_id') && options.activity_id > 0) {
      this.setData({
        activity_id: options.activity_id
      })
    } else {
      this.setData({
        activity_id: 794
      })
    }

    if (_object._length(options) > 0 && options.hasOwnProperty('clickid')) {
      //设置项目缓存
      this.setData({
        clickid: options.clickid
      })

      console.log(this.data.clickid);
    }

  },

  onShow() {
    //存参数
    _activity.set({
      'activity_id': this.data.activity_id,
      'tids': this.data.tids,
      'clickid': this.data.clickid
    })
    
    //有效期

    this.init_info();

    console.log(this.data.activity_id, '活动is - list');
  },
  // 项目信息
  init_info() {
    const { activity_id, tids } = this.data
    lib_activity.info(activity_id, tids).then((res) => {
      if (res.code != 0) {
        _layer.message(res.msg);
        return;
      }

      let data = res.data
      this.setData({
        share_theme: data.activity.share_theme,
        tid: data.activity.tid,
      })

      if (data.ui == null) {
        this.setData({ ui: {} })
        return;
      }
      this.setData({ ui: data.ui })

      // 项目结束
      if (!data.activity.state || (_time._current() > data.activity.etime)) {
        this.setData({
          is_stop: true
        })
        return;
      }


      /**城市 */
      // 判断是否有城市
      let city = []
      if (data.activity.city) {
        city = data.activity.city.split(',');
      }
      if (city.length == 1 && city[0] > 0) {
        //单城市项目
        this.setData({
          is_city: false
        })
      } else {
        //多城市项目
        this.setData({
          is_city: true
        })
        this.getCity(data.activity.city)
      }

      this.init_car(activity_id);
    })
  },

  // 城市
  getCity(city) {
    lib_city.list(city).then(res => {
      if (res.code != 0) {
        _layer.message(res.msg);
        return;
      }
      this.setData({
        citys: res.data
      })
      getApp().single_globalData.citys = res.data
    })
  },

  //该项目下的所有车型
  init_car(activity_id) {
    // 请求车型
    lib_car.seriessi(activity_id).then(res => {
      if (res.code != 0) {
        _layer.message(res.msg);
        return;
      }
      this.setData({
        allDataList: res.data,
        filteredDataList: res.data
      })
    })
  },


  //按钮 - 获取定位城市
  get_localCity(e) {
    this.getLocation(e)
  },
  getLocation(e) {
    const { id, name, msrp_max, msrp_min } = e.currentTarget.dataset.item
    const { activity_id, tids, clickid } = this.data

    /**价格 */
    let hide_msrp_max = (Number(msrp_min) * 1.1).toFixed(2).toString().split('.'); //成交底价 = 最低价*1.1
    hide_msrp_max[0] = '?'

    let hide_msrp_min = (Number(msrp_min) * 0.9).toFixed(2).toString().split('.'); //最低报价 = 最低价*0.9
    hide_msrp_min[0] = '?'

    let guiding_price = (Number(msrp_max) * 0.8).toFixed(2); //指导价 = 最高价*0.8

    getApp().single_globalData.msrp_max = hide_msrp_max[0] + '.' + hide_msrp_max[1];
    getApp().single_globalData.msrp_min = hide_msrp_min[0] + '.' + hide_msrp_min[1];
    getApp().single_globalData.guiding_price = msrp_min

    //存对应的车型
    // _series.set(this.data.activity_id, { 'series_name': name, 'series_id': id })
    _series.set({ 'series_name': name, 'series_id': id })

    tt.getLocation({
      type: 'gcj02',
      success: (res) => {
        if (res.errMsg == 'getLocation:ok') {
          // 定位到的城市信息（iOS 仅在抖音 / 抖音 Lite 20.5.0 及以上版本返回此字段）
          if (res.city) {
            this.data.citys.forEach((item, index) => {
              item.children.forEach((it, id) => {
                if (it.name == res.city) {
                  this.setData({
                    city: it.name,
                    province: item.name,
                    location: res.city
                  })
                }
                if (res.city == '北京市') {
                  this.setData({
                    city: '北京',
                    province: item.name,
                    location: res.city
                  })
                }
              })
            })
            _location.set(res.city)
            //存city
            _city.set(this.data.city)

          }
          // tt.navigateTo({
          //   url: `/pages/single/common/common`,
          // });
        }
      },
      fail: (errMsg) => {
        if (errMsg) {
          // _layer.message('已拒绝开启定位')
        }
      },
      complete:()=>{
        tt.navigateTo({
          url: `/pages/single/common/common`,
        });
        this.setData({
          searchValue: ''
        })
      }
    });
  },


  //数据绑定
  change_val(e) {
    const value = e.detail.value;
    const allDataList = this.data.allDataList;
    const filteredDataList = allDataList.filter(item => {
      return item.name.includes(value);
    });
    this.setData({
      searchValue: value,
      filteredDataList
    })

  },
  // 清空搜索
  clear_val(e) {
    this.setData({ searchValue: '' })
    this.setData({
      filteredDataList: [...this.data.allDataList]
    })
  },

  //分享
  async onShareAppMessage(option) {
    return {
      title: this.data.ui.share_theme ? this.data.ui.share_theme : '查询底价',
      path: `/pages/single/list/list?activity_id=${this.data.activity_id}&tids=${this.data.tids}&clickid=${this.data.clickid}`,
      imageUrl: this.data.ui.share ? this.data.ui.share : '/assets/image/banner.png', // 支持本地或远程图片，默认是小程序 icon
      success(res) {
        console.log('分享成功', res);
      },
      fail() {
        console.log("转发发布器调起失败");
      },
    };
  },

})